package com.active.test.queue.consumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy222
 * @create 2019-11-26 下午1:09
 */
@Slf4j
public class JmsConsumer_TX {
    private static final String ACTIVEMQ_URL = "tcp://localhost:61616";
    private static final String QUEUE_NAME = "queue01";

    public static void main(String[] args) throws JMSException, IOException {
        //1.创建连接工厂，按照给定的url地址，采用默认用户名和密码
        final ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2.通过连接工厂，获取连接的connection
        final Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();
        //3.创建会话
        // 两个参数，第一个叫事务，第二个叫签收
        final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        //4.创建目的地（具体是队列还是主题）
        final Queue queue = session.createQueue(QUEUE_NAME);
        //5.创建消费者
        final MessageConsumer consumer = session.createConsumer(queue);
        while (true) {
            final TextMessage textMsg = (TextMessage) consumer.receive(4000L);
            if (null != textMsg) {
                log.info("*********消费者接收到消息：{}", textMsg.getText());
            } else {
                break;
            }
        }
        consumer.close();
        session.commit();
        session.close();
        connection.close();
    }
}
